package cn.codesea.housework_user.utils;

import android.content.Context;
import android.content.SharedPreferences;

import com.google.gson.Gson;

import cn.codesea.housework_user.entity.User;
import cn.codesea.housework_user.entity.Worker;
import cn.codesea.housework_user.ui.LoginActivity;
import cn.codesea.housework_user.ui.ServiceActivity;

public class SPUtil {

    public static final String FILE_NAME = "share_data";// 本地存储文件名

    public static final String LOG_STATE = "log_state";// 登录状态 0 未登录，1 已登录
    public static final String USER = "user";// 记录已登录的用户信息,存入user实体，json格式。user 同时包含user、worker
    public static final String LOGIN_TYPE = "login_type";// 登录用户得类型 0 用户，1 工作人员，2 管理员

    public static final String USER_LOGIN = "0";
    public static final String WORKER_LOGIN = "1";
    public static final String MANAGER_LOGIN = "2";

    /**
     * 存值
     * @param context
     * @param key
     * @param str
     */
    public static void put(Context context, String key, String str){

        SharedPreferences sp = context.getSharedPreferences(FILE_NAME,Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();

        editor.putString(key,str);
        editor.commit();

    }

    /**
     * 取值
     * @param context
     * @param key
     * @param defaultStr
     * @return
     */
    public static String get(Context context, String key, String defaultStr){
        SharedPreferences sp = context.getSharedPreferences(FILE_NAME,Context.MODE_PRIVATE);
        return sp.getString(key,defaultStr);
    }

    /**
     * 判断是否登录
     * @return
     */
    public static boolean isLogin(Context context){
        boolean isLogin = false;
        int log_state = Integer.parseInt(get(context,LOG_STATE,"0"));
        if (log_state == 1){
            isLogin = true;
        }
        return isLogin;
    }

    /**
     * 登出
     * @param context
     */
    public static void logout(Context context){
        SPUtil.put(context,SPUtil.LOG_STATE,"0");
    }

    /**
     * 获取用户
     * @return
     */
    public static User getUser(Context context){
        User user = new Gson().fromJson(get(context,USER,""),User.class);
        return user;
    }

    public static Worker getWorker(Context context){
        return new Gson().fromJson(get(context,USER,""),Worker.class);
    }

    public static void loginSuccess(Context context,String user,String type){
        put(context,USER,user);
        put(context,LOGIN_TYPE,type);
        put(context,LOG_STATE,"1");
    }

    public static boolean isUser(Context context){
        boolean isUser = false;
        String login_type = get(context,LOGIN_TYPE,"0");
        if (USER_LOGIN.equals(login_type)){
            isUser = true;
        }
        return isUser;
    }

    public static String getLoginType(Context context){
        return get(context,LOGIN_TYPE,"");
    }

}
